<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片视图区域-->
    <el-card class="box-card">
      <!--      搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.rroleName" clearable @clear="getRolesList">
            <el-button slot="append" icon="el-icon-search" @click="getRolesList"></el-button>
          </el-input>
        </el-col>
        <!--      添加角色按钮区域-->
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--      角色列表区域-->
      <el-table :data="rolelist" border stripe>
        <!--        索引列-->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="rroleName"></el-table-column>
        <el-table-column label="角色表述" prop="rroleBase01"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.rroleId)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRightById(scope.row.rroleId)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--    分配权限的对话框-->
    <el-dialog
      title="提示"
      :visible.sync="setRightDialgVisible"
      width="50%" @close="setRightDialogClosed">
      <!--      树形控件-->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="roleId" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialgVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
    <!--    添加用户的对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!--      内容主题区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="rroleName">
          <el-input v-model="addForm.rroleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="rroleBase01">
          <el-input v-model="addForm.rroleBase01"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
    </el-dialog>
    <!--    修改角色的对话框-->
    <el-dialog
      title="编辑角色信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!--     内容主题 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="rroleName">
          <el-input v-model="editForm.rroleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="rroleBase01">
          <el-input v-model="editForm.rroleBase01"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部信息-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      editDialogVisible: false,
      //  根据id查询到的角色
      editForm: {},
      // 添加角色的表单数据
      addForm: {
        rroleName: '',
        rroleBase01: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        rroleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        rroleBase01: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 编辑表单的验证规则
      editFormRules: {
        rroleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        rroleBase01: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制添加表单的展示与隐藏
      addDialogVisible: false,
      //  获取角色列表的参数对象
      queryInfo: {
        // 获取角色列表的参数对象
        rroleName: '',
        // 当前的页数
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      //  所有角色列表数据
      rolelist: [],
      //  控制权限对话框的显示
      setRightDialgVisible: false,
      //  所有权限的数据
      rightsList: [],
      //  树形控件的属性绑定对象
      treeProps: {
        label: 'roleName',
        children: 'spRoles'
      },
      //  默认选中的节点ID值数组
      defKeys: [],
      //  当前分配权限的角色ID
      rroleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 展示编辑角色的对话框
    async showEditDialog (rroleId) {
      console.log('haha:' + this.editForm)
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('getrrolebyid', { params: { rroleId: rroleId } })
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.editForm = res.data
    },
    //  监听修改用户信息的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改角色信息
    editRoleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //  发起修改用户信息的数据请求
        const { data: res } = await this.$http.post('updaterrole', this.editForm)
        if (res.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        //  关闭对话框
        this.editDialogVisible = false
        //  刷新数据列表
        this.getRolesList()
        //  提示修改成功
        this.$message.success('更新用户信息成功!')
      })
    },
    //  获取所有角色的列表
    async getRolesList () {
      const { data: res } = await this.$http.get('getrroles', { params: this.queryInfo })
      if (res.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolelist = res.data.list
      this.total = res.data.total
    },
    // 点击按钮 添加角色
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        console.log(this.addForm)
        const { data: res } = await this.$http.post('addrrole', this.addForm)
        if (res.status !== 200) {
          return this.$message.error(res.msg)
        }
        this.$message.success('添加用户成功！')
        //  隐藏添加用户的对话框
        this.addDialogVisible = false
        // 获取用户列表信息
        this.getRolesList()
      })
    },
    // 监听pageSize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getRolesList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getRolesList()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 根据Id删除对应的权限
    async removeRightById (rroleId) {
      //  弹框提示用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //  如果用户确认删除，则返回值为字符串 confirm
      //  如果用户取消了删除，则返回值为字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      const { data: res } = await this.$http.get('deleterrolebyid', { params: { rroleId: rroleId } })
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success('删除用户成功！')
      this.getRolesList()
    },
    //  展示分配权限的对话框
    async showSetRightDialog (role) {
      console.log(role)
      this.rroleId = role.rroleId
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('getroleauths', { params: { rroleId: this.rroleId } })
      if (res.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      // 把获取的权限数据保存到data中
      this.rightsList = res.data
      for (let i = 0; i < this.rightsList.length; i++) {
        // 递归获取二级节点的ID
        this.getLeafKeys(this.rightsList[i], this.defKeys)
      }
      console.log(this.defKeys)
      this.setRightDialgVisible = true
    },
    //  通过递归的形式，获取角色下所有二级权限的id，并保存到defKeys数组中
    getLeafKeys (node, arr) {
      //  如果当前node节点不包含spRoles属性，则是二级节点=
      if (!node.spRoles && node.roleBase02 === 'true') {
        console.log(node.roleId)
        return arr.push(node.roleId)
      }
      if (node.spRoles) {
        node.spRoles.forEach(item =>
          this.getLeafKeys(item, arr))
      }
    },
    //  监听分配权限对话框的关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    //  点击为角色分配权限  获取每个权限的id
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      var param = new URLSearchParams()
      param.append('rroleId', this.rroleId)
      param.append('roleIds', idStr)
      const { data: res } = await this.$http.post('updateroleauths', param)
      if (res.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialgVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eeeeee;
  }

  .bdbottom {
    border-bottom: 1px solid #eeeeee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
